package com.symaster.backups.manager;

import com.symaster.backups.frame.MainFrame;
import lombok.Setter;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author yinmiao
 * @version 2024/2/20
 */
@Component
public class EventManager {

    private final Map<String, Set<EventRunnable>> eventMap = new HashMap<>();
    private final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1024));

    @Setter
    private MainFrame mainFrame;

    public void trigger(String key, Object param) {
        Set<EventRunnable> eventRunnable = eventMap.get(key);
        if (eventRunnable != null) {
            threadPool.execute(() -> {
                for (EventRunnable runnable : eventRunnable) {
                    if (!runnable.mainFrameVisible() || mainFrame.isVisible()) {
                        runnable.trigger(param);
                    }
                }
            });
        }
    }

    public void register(String key, EventRunnable runnable) {
        Set<EventRunnable> eventRunnableSet = eventMap.computeIfAbsent(key, k -> new HashSet<>());
        eventRunnableSet.add(runnable);
    }

    public void removeAllByKey(String key) {
        eventMap.remove(key);
    }
}
